<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<% String path = request.getContextPath() ;%>
<%@ taglib uri="/WEB-INF/tld/c.tld" prefix="c" %> 
<%@ taglib uri="/WEB-INF/tld/fmt.tld" prefix="fmt" %>
<%@ taglib uri="/WEB-INF/tld/ui.tld" prefix="ui" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
<jsp:include page="../../import.jsp" flush="true" />

<style>

</style>

</head>
<body class="iframeBody">
	<div class="Wrapper">
		<div>
			<form id="ligerForm">
				<div class="fieldset1 tabel_col clearFix">
					<div class="caption">
						<span class="title">借阅延期申请</span>
					</div>
					<div class="fieldBox col_50">
						<div class="label">合同号</div>
						<div class="field">
							${arcBorrowMainVO.contractNo}
						</div>
					</div>
					<div class="fieldBox col_50">
						<div class="label">交接单名称</div>
						<div class="field">
							${arcBorrowMainVO.arcReceiptName}
						</div>
					</div>
					<div class="fieldBox col_50">
						<div class="label">省公司档案袋编号</div>
						<div class="field">${arcBorrowMainVO.portfolioNumberProvince}
						</div>
					</div>
					<div class="fieldBox col_50">
						<div class="label">总部档案袋编号</div>
						<div class="field">${arcBorrowMainVO.portfolioNumber}
						</div>
					</div>
					
					<div class="caption">
						<span class="title">合同资料、承租人资料、担保人资料 ${arcBorrowMainVO.cstNm}  ${arcBorrowMainVO.contractNo}</span>
					</div>
					<div class="fieldBox col_100">
						<div style="width: 98%; margin-left: 1%;">
							<div id="gridContract" class="sq-grid"></div>
						</div>
					</div>
					
					<div class="caption">
						<span class="title">权证资料</span>
					</div>
					<c:forEach items="${paySchNoList}" var="item">
						<div class="fieldBox col_100">
						${item}
							<div style="width: 98%; margin-left: 1%;">
								<div id="gridPay${item}" class="sq-grid"></div>
							</div>
						</div>
					</c:forEach>
					
					<div class="caption">
						<span class="title">申请人邮寄信息</span>
					</div>
					
					<div class="fieldBox col_100">
						<div style="width: 98%; margin-left: 1%;">
							<div id="gridProposerPostInfo" class="sq-grid"></div>
						</div>
					</div>
					
					<div class="caption">
						<span class="title">邮寄信息</span>
					</div>
					
					<div class="fieldBox col_100">
						<div style="width: 98%; margin-left: 1%;">
							<div id="gridPostInfo" class="sq-grid"></div>
						</div>
					</div>
					
					<div class="fieldBox col_100">
						<div class="label">延期原因</div>
						<div class="field">
							 <textarea id="delayReason"  name="delayReason" rows="3" class="l-textarea" style="width:100%">${arcBorrowMainVO.delayReason}</textarea>
						</div>
					</div>
					
					<c:if test="${from == 'delayApply'}">
				        <div class="btnsBox">
								<span id="saveBtn" class="sq-button sq-button-round" onclick="delayApplySave();">发起延期申请</span>
						</div>
					</c:if>
					<c:if test="${from == 'delayUpdate'}">
				        <div class="btnsBox">
								<span id="saveBtn" class="sq-button sq-button-round" onclick="delayApplySave('save');">保存</span>
						</div>
					</c:if>
			</form>
				
		</div>
	</div>
	<script type="text/javascript">
	     var  contractNo = "${arcBorrowMainVO.contractNo}";//合同号
	     var  paySchNoList = "${paySchNoListStr}";//多个支付表号
	     
		$(function() {
			$("#ligerForm").ligerForm();
			
			initGrid();//初始化数据：合同明细、支付表明细、邮寄信息
	    });
		
		
		function initGrid(){
			//1、初始化合同明细
			if(contractNo !="") {
				createGrid("gridContract",1);
			}
			
			//2、初始化权证资料明细
			<c:forEach items="${paySchNoList}" var="item">
				createGrid("gridPay${item}",2,"${item}");//创建ligerGrid
				
			</c:forEach>
			
			//3、初始化申请人邮寄信息
			createPostInfoGrid("gridProposerPostInfo","1","130");
			
			//4、初始化邮寄信息
			createPostInfoGrid("gridPostInfo","2;3;4;5","200");
			
			
		}
	     
		function createGrid(gridId,arcLevel,payListCode){
		     
			var _url = '<%=path%>/archive/arcBorrowMain/arcBorrowDetailList.do?arcBorrowMainId=${arcBorrowMainVO.id}&arcLevel='+arcLevel;
			if(payListCode) {
				_url += '&payListCode='+payListCode;
			}
			
			$("#"+gridId).ligerGrid({
				url:_url,
				method:'get',
				columns:[
					{ display: '权证类别', name: 'fileFlagNm',type:'text'},
					{ display: '权证名称', name: 'fileName',type:'text'},
					{display:'资料类型', name: 'dossierTempNm'},
					{display:'扫描件', name: 'arcMgrDetailVO.scanAttcheList', 
						 render: function (rowdata, rowindex, value) {
	                            var h = '<div class="gridNanoItems">';
	                            $(value).each(function(index, el) {
	                                h = h + '<div class="ellipsis"><a class="curPointer" href="javascript:downFile(';
	                                h+="'"+el.filePath+"'";
	                                h+=",'"+el.fileNm+"'";
	                                h+=')">'+el.fileNm+'</a></div>';
	                            });
	                            return h + '</div>';
	                        }
						},
					{display:'归档地点', name: 'arcMgrDetailVO.arcReceiptDetailVO.arcPlaceNm'},
					//{display:'存档份数',name: 'arcMgrDetailVO.dossierCountT',type:'int'},
					{display:'是否归还',name: 'originalReturnNm'},
					{display:'计划归还日期', name: 'returnDate',type: 'date',render:renderDate},
					{display:'归还状态', name: 'returnStateNm'},
					/* {display:'实际归还日期', 
						  render: function (item) {
			                    return renderDate(item.realReturnDate);
			                }
					}, */
					{ display: '延期至', name: 'delayDate', type: 'date',render:renderDate,editor: { type: 'date' } }
					
				],onBeforeSubmitEdit: function (e) {
		        
		        },
		        <c:if test="${from == 'delayApply' || from == 'delayUpdate'}">
			        enabledEdit: true,
			        checkbox:true,//列表是否有选择框
				</c:if>
		        
				usePager: false,//是否有分页便签
				isScroll: true,//是否有滚动条
				root:'rows',
				record:'total',
				hideLoadButton:false,
				width:'100%',
				height:'200',
				heightDiff:-2,
				rownumbers:true,//列表是否有行号
				selectRowButtonOnly:true,//复选框模式时，是否只允许点击复选框才能选择行
				//选择行事件
				onSelectRow: function(rowdata, rowid, rowobj){
					
				},
				//取消选择行事件
				onUnSelectRow : function(rowdata, rowid, rowobj){
				},
	            onBeforeCheckRow: function (checked, data, rowindex, rowobj) {
	                if (data.originalReturn == 2){
	                	$.ligerDialog.SQalert({content: "不归还的资料，无需勾选",SQ_type: "warning"});
	                    return false;
	                }
	                return true;
	            },
	            onBeforeEdit: f_onBeforeEdit0
	            ,
	            onAfterShowData: function () {
                    setNanoScroller();//设置附件列表每行高度
                }
			});
		}
		
		 //表格列待编辑事件
	    function f_onBeforeEdit0(e) { 
	        if (e.column.name == "delayDate") {
	        	var gridId = "gridContract";
	        	if(e.record.arcLevel == 2) {
	        		gridId = "gridPay"+e.record.paylistCode;
	        	}
	        	
	        	var manager = $("#"+gridId).ligerGetGridManager();
				if(manager.isSelected(e.rowindex)){
					return true;
				}else{
					$.ligerDialog.SQalert({content: '请选中该记录后，再编辑!',SQ_type: "error",SQ_showButtons: true});
					return false;
				}
	        }
	        return true;
	    }
		 
		function createPostInfoGrid(gridId,arcAppBussTypes,_height){
		     
			$("#"+gridId).ligerGrid({
				url:'<%=path%>/archive/arcBorrowMain/arcPostInfoList.do?arcAppId=${arcBorrowMainVO.id}&arcAppBussTypes='+arcAppBussTypes,
				method:'get',
				columns:getColumns(gridId),
				onBeforeSubmitEdit: function (e) {
		        
		        },
			    enabledEdit: false,
				usePager: false,//是否有分页便签
				isScroll: true,//是否有滚动条
				root:'rows',
				record:'total',
				hideLoadButton:false,
				width:'100%',
				height:_height,
				fixedCellHeight: false,
				heightDiff:-2,
				//checkbox:true,//列表是否有选择框
				rownumbers:true,//列表是否有行号
				selectRowButtonOnly:true,//复选框模式时，是否只允许点击复选框才能选择行
				//选择行事件
				onSelectRow: function(rowdata, rowid, rowobj){
					
				},
				//取消选择行事件
				onUnSelectRow : function(rowdata, rowid, rowobj){
				},
				onBeforeCheckRow: function (checked, data, rowindex, rowobj) {
	            },
			});
		}
		
		function getColumns(gridId){
			var col_data = [
							{ display: '地址类型', name: 'arcAppBussTypeNm',type:'text'},
							{ display: '收件人（工号）', name: 'idCard',type:'text'},
							{ display: '收件人（姓名）', name: 'recipient',type:'text'},
							{ display: '联系电话', name: 'mobile',type:'text'},
							{ display: '邮寄方式', name: 'sendTypeNm',type:'text'},
							{ display: '地址', name: 'sendAddr',type:'text',isEllipsis: false}
							
						];
			if(gridId =="gridProposerPostInfo") {
				col_data.push({ display: '借阅类型', name: 'borrowTypeNm',type:'text'});
				col_data.push({ display: '借阅用途', name: 'borrowUseNm',type:'text',isEllipsis: false});
				col_data.push({ display: '借阅备注', name: 'borrowRemark',type:'text',isEllipsis: false});
			}else {
				col_data.push({ display: '物流公司', name: 'sendCompanyNm',type:'text'});
				col_data.push({ display: '快递单号', name: 'sendNum',type:'text'});
			}
			
			return col_data;
		}
		 
		
		  
		//发起借阅延期申请
		function delayApplySave(operate){
			
			//1、验证是否勾选
			//合同类明细 
			var _arcBorrowDetailList =  liger.get("gridContract").getSelectedRows();
			// 支付表类明细
			 if(paySchNoList !="") {
				var paySchNoArray = paySchNoList.split(",");
				for(var i=0;i<paySchNoArray.length;i++) {
					var gridPayArray = liger.get("gridPay"+paySchNoArray[i]).getSelectedRows();
					for(var j=0;j<gridPayArray.length;j++) {
						_arcBorrowDetailList.push(gridPayArray[j]);
					}
				}
			}
			if(_arcBorrowDetailList.length == 0) {
				$.ligerDialog.SQalert({content: "请勾选资料",SQ_type: "warning"});
				return ;
			}
			
			//2、检查是否输入：延期至是否选择 
			//2.1 合同列表
			 if(contractNo !="") {
				if(!checkDelayDate("gridContract")) return;
			}
			//2.2 支付表类
			if(paySchNoList !="") {
				var paySchNoArray = paySchNoList.split(",");
				for(var i=0;i<paySchNoArray.length;i++) {
					if(!checkDelayDate("gridPay"+paySchNoArray[i])) return;
				}
			} 
			
			
		   
			//3 、组织数据，提交后台
			var ligerForm = liger.get("ligerForm");
			var data = ligerForm.getData();
			data["contractNo"] =contractNo;
			
			
			
			data["_arcBorrowDetailList"] = JSON.stringify(_arcBorrowDetailList);
			data["id"] = "${arcBorrowMainVO.id}";
			data["from"] = "${from}";
			
			console.log(data);
			//return;
			var tip ;
			if(operate == "save") {
				tip ="确认保存吗";
			}else {
				tip ="发起延期申请吗";
			}
			
			$.ligerDialog.confirm(tip, function (flag) {
				if(!flag) return;
				var wait_dialog = null;
				$.ajax({
					type: 'post',
					dataType: 'json',
					data: data,
					url: '<%=path%>/archive/arcBorrowMain/delayApplySave.do?',
					beforeSend: function(){
						wait_dialog=$.ligerDialog.SQalert({content: LogUtils.LOG_CMM_DATA_LOADING ,SQ_type: "waitting"});
					},success:function(msg){
						wait_dialog.close();
						if(msg.success == 1){
								alert(msg.info);
								if(operate !="save") {
									Remove_navTab();//关闭当前页面
								}
						}else{
							$.ligerDialog.SQalert({content: msg.info,SQ_type: "error",SQ_showButtons: true});
						}
					},error:function (XMLHttpRequest, textStatus, errorThrown) { 
						wait_dialog.close();
						$.ligerDialog.SQalert({content: "网络错误，请稍后重试",SQ_type: "error",SQ_showButtons: true});
					} 
				});
			});
		}
		
		
		function checkDelayDate(gridId){
			var selectedRows = liger.get(gridId).getSelectedRows();
			for (var i=0; i< selectedRows.length; i++){ 
				//console.log(selectedRows[i].delayDate);
				if(!selectedRows[i].delayDate) {
					$.ligerDialog.SQalert({content: selectedRows[i].fileFlag+"-"+selectedRows[i].fileName+"，请选择延期日期",SQ_type: "warning"});
					return false;
				}
				//延期时间需要大于归还日期
				/* console.log(selectedRows[i].delayDate);
				console.log(renderDate(null,null,selectedRows[i].returnDate));
				console.log(selectedRows[i].delayDate <= renderDate(null,null,selectedRows[i].returnDate)); */
				if(selectedRows[i].delayDate <= renderDate(null,null,selectedRows[i].returnDate)) {
					$.ligerDialog.SQalert({content: selectedRows[i].fileFlag+"-"+selectedRows[i].fileName+"，请选择延期日期需要大于计划归还日期",SQ_type: "warning"});
					return false;
				}
    		}
			return true;
		}
		
	
		
		function renderDate(rowdata, index, value){
			var dateStr = "";
			if(value != null && value !=""){
				var date = new Date(value);
				dateStr = DateUtils.formatDate(date, DateUtils.YYYY_MM_DD);
			}
			return dateStr;
		}	
			
		//设置附件列表每行高度
		 function setNanoScroller () {
	         $('.gridNanoItems').each(function(index, el) {
	             if ($(el).height() > 100 ) {
	            	 $(el).wrap('<div class="gridNanoContainer"><div class="nano"><div class="nano-content">');
	                 $(el).parents('.gridNanoContainer').height(100);
	                 $(".nano").nanoScroller({
	                     preventPageScrolling: true
	                 });
	             };
	         });
	     }
		//下载文件
		function downFile(_url,_name){
			if(SQ.regs.img.test(_name)){
				SQ.imgPreview(_url, true);
			}else{
				window.open(_url);
			}
		}
		
		
	</script>
</body>
</html>